// pages/chat/chat.js
//导入共享数据包
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'

var socket = null

Page({

    //共享数据相关配置
    options: {
        styleIsolation: 'shared'
    },
    
    behaviors: [storeBindingsBehavior],

    //引入需要的共享数据
    storeBindings: {
        store,
        fields: {
            chatDto: 'chatDto',
            token: 'token',
            userInfo: 'userInfo'
        },
        actions: {
            updateChatDto: 'updateChatDto'
        }
    },

    /**
     * 页面的初始数据
     */
    data: {
        //聊天记录
        chatRecords: [],
        //聊天信息
        inputMessage: null
    },

    //WebSocket消息通知方法
    MessageWebSocket() {
        socket.send({
            data: '{"sid":"'+ store.chatDto.userFriendId +'","message":"啦啦啦"}',
            success: (res) => {
                console.info('客户端发送成功');
            }
        });
    },

    //监听消息框内容修改
    onMessageChange(e) {
        this.setData({
            inputMessage: e.detail.value
        })
    },

    //发送消息
    sendMessage() {

        //判断发送消息是否为空
        if(!this.data.inputMessage) {
            wx.showToast({
                title: '发送消息为空！',
                icon: 'error'
              })
            return
        }

        //展示加载框
        wx.showLoading({
            title: '消息发送中...',
          })

        //请求后端
        wx.request({
          url: `${store.programURL}/chat/sendMessage`,
          method: 'POST',
          data: {
            userId: store.userInfo.id,
            userName: store.userInfo.nickname,
            content: this.data.inputMessage,
            targetUserId: store.chatDto.userFriendId,
            targetUserName: store.chatDto.userFriendName
          },
          header: {
            authentication: store.token
          },
          success: (e) => {
            console.log(e)
            if(e.data.code != 1) {
              wx.showToast({
                  title: '消息发送失败！',
                  icon: 'error'
                })
              return
            }
            wx.showToast({
              title: '消息发送成功！',
            })
            //上传成功后清空页面数据
            this.setData({
              inputMessage: null
            })

            //测试WebSocket
            this.MessageWebSocket()

        },
        complete: () => {
          wx.hideLoading()
          this.getChatRecords()
        }
      })

    },

    //获取聊天记录
    getChatRecords() {
        console.log('刷新了聊天记录...')
        wx.request({
          url: `${store.programURL}/chat/getChatRecords`,
          method: 'POST',
          header: {
            authentication: store.token
          },
          data: {
            userId: store.chatDto.userId,
            targetUserId: store.chatDto.userFriendId
          },
          success: (res) => {
            console.log(res)
            this.setData({
                chatRecords: res.data.data
            })
          }
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        socket = wx.connectSocket({
            url: `ws://localhost:8880/webSocket/${store.userInfo.id}`,
            success: (res) => {
                console.info(res);
            }
        })

        //开启事件监听
        socket.onOpen(function () {
            console.info('连接打开成功');
        })
        socket.onClose(function () {
            console.info('连接关闭成功');
        })
        socket.onError(function () {
            console.info('连接报错');
        })
        socket.onMessage((e) => {
            console.info('收到来自服务端的消息！')
            console.info(e)
            this.getChatRecords()
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        console.log(store)
        wx.setNavigationBarTitle({
            title: store.chatDto.userFriendName,
          })
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        //this.getChatRecords()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        wx.closeSocket()
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})